<?php

namespace app\api\controller\v1;

use app\common\exception\Client;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\response\Json;
use app\api\validate\UserAddress as UserAddressValidate;
use app\common\service\UserAddress as UserAddressService;

class UserAddress
{

    /**
     * 保存用户地址
     * @param Request $request
     * @return Json
     * @throws Client
     */
    public function save(Request $request): Json
    {
            // 验证参数
            $params = $request->only(['name', 'mobile', 'detail', 'comunum']);
            $validate = new UserAddressValidate();
            if(!$validate->check($params))throw new Client(223001,$validate->getError());
            $token = $request->header('token');
            if (!$token)throw new Client(223001,'缺少Token');
            // 调用服务层
            $service = new UserAddressService();
            $address = $service->saveUserAddress($params,$token);

            return writeJson(200,$address,'保存地址成功');
    }

    /**
     * 获取用户地址
     * @param Request $request
     * @return Json
     * @throws Client
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function get(Request $request): Json
    {
            // 调用服务层
            $service = new UserAddressService();
            $token = $request->header('token');
            if (!$token)throw new Client(223001,'缺少Token');
            $address = $service->getUserAddress($token);

            return writeJson(200,$address,'获取地址成功');
    }
}